export class ReadCache {
	constructor(read=function(callback=function(data){}){}, origin={}) {
		this.data = origin
		this.read = read
		this.state = 'INIT'  // INIT | READING | DONE | REREADING
		this.callbacks = []
	}

	get(callback=function(data){}) {
		var that = this
		if (that.state == 'INIT') {
			that.state = 'READING'
			that.read(function(data) {
				that.data = data
				callback(that.data)
				that.state = 'DONE'
				// Call hangup callbacks.
				while (that.callbacks.length > 0) {
					var cb = that.callbacks.shift()
					cb(data)
				}
			})
		}
		else if (that.state == 'READING') {
			that.callbacks.push(callback)
		}
		else if (that.state == 'DONE') {
			callback(that.data)
		}
		else if (that.state == 'REREADING') {
			callback(that.data)
		}
	}

	reset() {
		this.state = 'INIT'
	}
}